package com.lyl.mysqlmonitor.statement;

import com.lyl.mysqlmonitor.SqlAnalyzer;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 监控PreparedStatement类
 * 代理真实的PreparedStatement，拦截execute/executeQuery方法
 */
public class MonitorPreparedStatement implements PreparedStatement {

    private static final Logger LOGGER = LoggerFactory.getLogger(MonitorPreparedStatement.class);
    private final PreparedStatement realStatement;
    private final String sql;
    private final List<Object> parameters;

    public MonitorPreparedStatement(PreparedStatement realStatement, String sql) {
        this.realStatement = realStatement;
        this.sql = sql;
        this.parameters = new ArrayList<>();
        LOGGER.debug("创建 MonitorPreparedStatement, SQL: {}", sql);
    }

    @Override
    public ResultSet executeQuery() throws SQLException {
        // 分析SQL
        LOGGER.debug("执行查询: {}", sql);
        SqlAnalyzer.analyze(sql, parameters, realStatement.getConnection());
        // 执行实际查询
        return realStatement.executeQuery();
    }

    @Override
    public int executeUpdate() throws SQLException {
        return realStatement.executeUpdate();
    }

    @Override
    public void setNull(int parameterIndex, int sqlType) throws SQLException {
        realStatement.setNull(parameterIndex, sqlType);
        if (parameterIndex >= parameters.size() + 1) {
            // 扩展列表以容纳新参数
            while (parameters.size() < parameterIndex) {
                parameters.add(null);
            }
        } else {
            parameters.set(parameterIndex - 1, null);
        }
    }

    @Override
    public void setBoolean(int parameterIndex, boolean x) throws SQLException {
        realStatement.setBoolean(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setByte(int parameterIndex, byte x) throws SQLException {
        realStatement.setByte(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setShort(int parameterIndex, short x) throws SQLException {
        realStatement.setShort(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setInt(int parameterIndex, int x) throws SQLException {
        realStatement.setInt(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setLong(int parameterIndex, long x) throws SQLException {
        realStatement.setLong(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setFloat(int parameterIndex, float x) throws SQLException {
        realStatement.setFloat(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setDouble(int parameterIndex, double x) throws SQLException {
        realStatement.setDouble(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setBigDecimal(int parameterIndex, java.math.BigDecimal x) throws SQLException {
        realStatement.setBigDecimal(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setString(int parameterIndex, String x) throws SQLException {
        realStatement.setString(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setBytes(int parameterIndex, byte[] x) throws SQLException {
        realStatement.setBytes(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setDate(int parameterIndex, java.sql.Date x) throws SQLException {
        realStatement.setDate(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setTime(int parameterIndex, java.sql.Time x) throws SQLException {
        realStatement.setTime(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setTimestamp(int parameterIndex, java.sql.Timestamp x) throws SQLException {
        realStatement.setTimestamp(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setAsciiStream(int parameterIndex, java.io.InputStream x, int length) throws SQLException {
        realStatement.setAsciiStream(parameterIndex, x, length);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setUnicodeStream(int parameterIndex, java.io.InputStream x, int length) throws SQLException {
        realStatement.setUnicodeStream(parameterIndex, x, length);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setBinaryStream(int parameterIndex, java.io.InputStream x, int length) throws SQLException {
        realStatement.setBinaryStream(parameterIndex, x, length);
        setParameter(parameterIndex, x);
    }

    @Override
    public void clearParameters() throws SQLException {
        realStatement.clearParameters();
        parameters.clear();
    }

    @Override
    public void setObject(int parameterIndex, Object x, int targetSqlType) throws SQLException {
        realStatement.setObject(parameterIndex, x, targetSqlType);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setObject(int parameterIndex, Object x) throws SQLException {
        realStatement.setObject(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public boolean execute() throws SQLException {
        // 分析SQL
        LOGGER.debug("执行SQL: {}", sql);
        SqlAnalyzer.analyze(sql, parameters, realStatement.getConnection());
        // 执行实际SQL
        return realStatement.execute();
    }

    @Override
    public void addBatch() throws SQLException {
        realStatement.addBatch();
    }

    @Override
    public void setCharacterStream(int parameterIndex, java.io.Reader reader, int length) throws SQLException {
        realStatement.setCharacterStream(parameterIndex, reader, length);
        setParameter(parameterIndex, reader);
    }

    @Override
    public void setRef(int parameterIndex, java.sql.Ref x) throws SQLException {
        realStatement.setRef(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setBlob(int parameterIndex, java.sql.Blob x) throws SQLException {
        realStatement.setBlob(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setClob(int parameterIndex, java.sql.Clob x) throws SQLException {
        realStatement.setClob(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setArray(int parameterIndex, java.sql.Array x) throws SQLException {
        realStatement.setArray(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public java.sql.ResultSetMetaData getMetaData() throws SQLException {
        return realStatement.getMetaData();
    }

    @Override
    public void setDate(int parameterIndex, java.sql.Date x, java.util.Calendar cal) throws SQLException {
        realStatement.setDate(parameterIndex, x, cal);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setTime(int parameterIndex, java.sql.Time x, java.util.Calendar cal) throws SQLException {
        realStatement.setTime(parameterIndex, x, cal);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setTimestamp(int parameterIndex, java.sql.Timestamp x, java.util.Calendar cal) throws SQLException {
        realStatement.setTimestamp(parameterIndex, x, cal);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setNull(int parameterIndex, int sqlType, String typeName) throws SQLException {
        realStatement.setNull(parameterIndex, sqlType, typeName);
        setParameter(parameterIndex, null);
    }

    @Override
    public void setURL(int parameterIndex, java.net.URL x) throws SQLException {
        realStatement.setURL(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public java.sql.ParameterMetaData getParameterMetaData() throws SQLException {
        return realStatement.getParameterMetaData();
    }

    @Override
    public void setRowId(int parameterIndex, java.sql.RowId x) throws SQLException {
        realStatement.setRowId(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setNString(int parameterIndex, String value) throws SQLException {
        realStatement.setNString(parameterIndex, value);
        setParameter(parameterIndex, value);
    }

    @Override
    public void setNCharacterStream(int parameterIndex, java.io.Reader value, long length) throws SQLException {
        realStatement.setNCharacterStream(parameterIndex, value, length);
        setParameter(parameterIndex, value);
    }

    @Override
    public void setNClob(int parameterIndex, java.sql.NClob value) throws SQLException {
        realStatement.setNClob(parameterIndex, value);
        setParameter(parameterIndex, value);
    }

    @Override
    public void setClob(int parameterIndex, java.io.Reader reader, long length) throws SQLException {
        realStatement.setClob(parameterIndex, reader, length);
        setParameter(parameterIndex, reader);
    }

    @Override
    public void setBlob(int parameterIndex, java.io.InputStream inputStream, long length) throws SQLException {
        realStatement.setBlob(parameterIndex, inputStream, length);
        setParameter(parameterIndex, inputStream);
    }

    @Override
    public void setNClob(int parameterIndex, java.io.Reader reader, long length) throws SQLException {
        realStatement.setNClob(parameterIndex, reader, length);
        setParameter(parameterIndex, reader);
    }

    @Override
    public void setSQLXML(int parameterIndex, java.sql.SQLXML xmlObject) throws SQLException {
        realStatement.setSQLXML(parameterIndex, xmlObject);
        setParameter(parameterIndex, xmlObject);
    }

    @Override
    public void setAsciiStream(int parameterIndex, java.io.InputStream x, long length) throws SQLException {
        realStatement.setAsciiStream(parameterIndex, x, length);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setBinaryStream(int parameterIndex, java.io.InputStream x, long length) throws SQLException {
        realStatement.setBinaryStream(parameterIndex, x, length);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setCharacterStream(int parameterIndex, java.io.Reader reader, long length) throws SQLException {
        realStatement.setCharacterStream(parameterIndex, reader, length);
        setParameter(parameterIndex, reader);
    }

    @Override
    public void setAsciiStream(int parameterIndex, java.io.InputStream x) throws SQLException {
        realStatement.setAsciiStream(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setBinaryStream(int parameterIndex, java.io.InputStream x) throws SQLException {
        realStatement.setBinaryStream(parameterIndex, x);
        setParameter(parameterIndex, x);
    }

    @Override
    public void setCharacterStream(int parameterIndex, java.io.Reader reader) throws SQLException {
        realStatement.setCharacterStream(parameterIndex, reader);
        setParameter(parameterIndex, reader);
    }

    @Override
    public void setNCharacterStream(int parameterIndex, java.io.Reader value) throws SQLException {
        realStatement.setNCharacterStream(parameterIndex, value);
        setParameter(parameterIndex, value);
    }

    @Override
    public void setClob(int parameterIndex, java.io.Reader reader) throws SQLException {
        realStatement.setClob(parameterIndex, reader);
        setParameter(parameterIndex, reader);
    }

    @Override
    public void setBlob(int parameterIndex, java.io.InputStream inputStream) throws SQLException {
        realStatement.setBlob(parameterIndex, inputStream);
        setParameter(parameterIndex, inputStream);
    }

    @Override
    public void setNClob(int parameterIndex, java.io.Reader reader) throws SQLException {
        realStatement.setNClob(parameterIndex, reader);
        setParameter(parameterIndex, reader);
    }

    @Override
    public ResultSet executeQuery(String sql) throws SQLException {
        // 分析SQL
        LOGGER.debug("执行查询(带SQL): {}", sql);
        SqlAnalyzer.analyze(sql, realStatement.getConnection());
        // 执行实际查询
        return realStatement.executeQuery(sql);
    }

    @Override
    public int executeUpdate(String sql) throws SQLException {
        return realStatement.executeUpdate(sql);
    }

    @Override
    public void close() throws SQLException {
        realStatement.close();
    }

    @Override
    public int getMaxFieldSize() throws SQLException {
        return realStatement.getMaxFieldSize();
    }

    @Override
    public void setMaxFieldSize(int max) throws SQLException {
        realStatement.setMaxFieldSize(max);
    }

    @Override
    public int getMaxRows() throws SQLException {
        return realStatement.getMaxRows();
    }

    @Override
    public void setMaxRows(int max) throws SQLException {
        realStatement.setMaxRows(max);
    }

    @Override
    public void setEscapeProcessing(boolean enable) throws SQLException {
        realStatement.setEscapeProcessing(enable);
    }

    @Override
    public int getQueryTimeout() throws SQLException {
        return realStatement.getQueryTimeout();
    }

    @Override
    public void setQueryTimeout(int seconds) throws SQLException {
        realStatement.setQueryTimeout(seconds);
    }

    @Override
    public void cancel() throws SQLException {
        realStatement.cancel();
    }

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return realStatement.getWarnings();
    }

    @Override
    public void clearWarnings() throws SQLException {
        realStatement.clearWarnings();
    }

    @Override
    public void setCursorName(String name) throws SQLException {
        realStatement.setCursorName(name);
    }

    @Override
    public boolean execute(String sql) throws SQLException {
        // 分析SQL
        LOGGER.debug("执行SQL(带SQL): {}", sql);
        SqlAnalyzer.analyze(sql, realStatement.getConnection());
        // 执行实际SQL
        return realStatement.execute(sql);
    }

    @Override
    public ResultSet getResultSet() throws SQLException {
        return realStatement.getResultSet();
    }

    @Override
    public int getUpdateCount() throws SQLException {
        return realStatement.getUpdateCount();
    }

    @Override
    public boolean getMoreResults() throws SQLException {
        return realStatement.getMoreResults();
    }

    @Override
    public void setFetchDirection(int direction) throws SQLException {
        realStatement.setFetchDirection(direction);
    }

    @Override
    public int getFetchDirection() throws SQLException {
        return realStatement.getFetchDirection();
    }

    @Override
    public void setFetchSize(int rows) throws SQLException {
        realStatement.setFetchSize(rows);
    }

    @Override
    public int getFetchSize() throws SQLException {
        return realStatement.getFetchSize();
    }

    @Override
    public int getResultSetConcurrency() throws SQLException {
        return realStatement.getResultSetConcurrency();
    }

    @Override
    public int getResultSetType() throws SQLException {
        return realStatement.getResultSetType();
    }

    @Override
    public void addBatch(String sql) throws SQLException {
        realStatement.addBatch(sql);
    }

    @Override
    public void clearBatch() throws SQLException {
        realStatement.clearBatch();
    }

    @Override
    public int[] executeBatch() throws SQLException {
        return realStatement.executeBatch();
    }

    @Override
    public Connection getConnection() throws SQLException {
        return realStatement.getConnection();
    }

    @Override
    public boolean getMoreResults(int current) throws SQLException {
        return realStatement.getMoreResults(current);
    }

    @Override
    public ResultSet getGeneratedKeys() throws SQLException {
        return realStatement.getGeneratedKeys();
    }

    @Override
    public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException {
        return realStatement.executeUpdate(sql, autoGeneratedKeys);
    }

    @Override
    public int executeUpdate(String sql, int[] columnIndexes) throws SQLException {
        return realStatement.executeUpdate(sql, columnIndexes);
    }

    @Override
    public int executeUpdate(String sql, String[] columnNames) throws SQLException {
        return realStatement.executeUpdate(sql, columnNames);
    }

    @Override
    public boolean execute(String sql, int autoGeneratedKeys) throws SQLException {
        // 分析SQL
        SqlAnalyzer.analyze(sql, realStatement.getConnection());
        // 执行实际SQL
        return realStatement.execute(sql, autoGeneratedKeys);
    }

    @Override
    public boolean execute(String sql, int[] columnIndexes) throws SQLException {
        // 分析SQL
        SqlAnalyzer.analyze(sql, realStatement.getConnection());
        // 执行实际SQL
        return realStatement.execute(sql, columnIndexes);
    }

    @Override
    public boolean execute(String sql, String[] columnNames) throws SQLException {
        // 分析SQL
        SqlAnalyzer.analyze(sql, realStatement.getConnection());
        // 执行实际SQL
        return realStatement.execute(sql, columnNames);
    }

    @Override
    public int getResultSetHoldability() throws SQLException {
        return realStatement.getResultSetHoldability();
    }

    @Override
    public boolean isClosed() throws SQLException {
        return realStatement.isClosed();
    }

    @Override
    public void setPoolable(boolean poolable) throws SQLException {
        realStatement.setPoolable(poolable);
    }

    @Override
    public boolean isPoolable() throws SQLException {
        return realStatement.isPoolable();
    }

    @Override
    public void closeOnCompletion() throws SQLException {
        realStatement.closeOnCompletion();
    }

    @Override
    public boolean isCloseOnCompletion() throws SQLException {
        return realStatement.isCloseOnCompletion();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        return realStatement.unwrap(iface);
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        return realStatement.isWrapperFor(iface);
    }

    @Override
    public void setObject(int parameterIndex, Object x, int targetSqlType, int scale) throws SQLException {
        realStatement.setObject(parameterIndex, x, targetSqlType, scale);
        setParameter(parameterIndex, x);
    }

    /**
     * 设置参数，处理参数索引（JDBC索引从1开始，List从0开始）
     * @param parameterIndex JDBC参数索引（从1开始）
     * @param value 参数值
     */
    private void setParameter(int parameterIndex, Object value) {
        // 确保列表大小足够
        while (parameters.size() < parameterIndex) {
            parameters.add(null);
        }
        // 设置参数值
        parameters.set(parameterIndex - 1, value);
    }
}
